package cool.taomu.toolkit.jxls

import java.io.InputStream
import java.io.OutputStream
import java.util.HashMap
import java.util.List
import java.util.Map
import java.util.function.Function
import java.util.regex.Matcher
import java.util.regex.Pattern
import org.jxls.area.Area
import org.jxls.builder.AreaBuilder
import org.jxls.builder.xls.XlsCommentAreaBuilder
import org.jxls.common.CellRef
import org.jxls.common.Context
import org.jxls.util.JxlsHelper

class JxlsToolKit {

	def void execute(InputStream input, OutputStream output, Function<Void, Map<String, Object>>[] funcs) {
		var transformer = JxlsHelper.getInstance().createTransformer(input, output);
		var AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer);
		val List<Area> areas = areaBuilder.build();
		val rowsMap = new HashMap<String, Integer>();
		funcs.forEach [
			var resultMap = it.apply(null)
			resultMap.forEach [ k, v |
				if (rowsMap.containsKey(k)) {
					var int rows = rowsMap.get(k);
					if (v instanceof List) {
						rowsMap.put(k, rows + v.size);
					}
					areasWrite(areas, rows, k, v);
				} else {
					if (v instanceof List) {
						rowsMap.put(k, v.size);
						areasWrite(areas, 0, k, v);
					}
				}
			]
		]
		transformer.write
	}

	private def void areasWrite(List<Area> areas, int rows, String k, Object v) {
		val Context context = new Context();
		context.putVar(k, v)
		areas.forEach [ area |
			var originalCellName = area.getStartCellRef().getCellName();
			var shiftedCellName = shiftDown(originalCellName, rows); // 向下偏移10行
			var cellRef = new CellRef(shiftedCellName);
			area.applyAt(cellRef, context);
		]
	}

	// 工具方法：向下偏移 n 行
	private  def String shiftDown(String cellName, int rows) {
		var Matcher matcher = Pattern.compile("([\u4e00-\u9fff|A-Za-z\\d!]+)(\\d+)").matcher(cellName);
		if(!matcher.matches()) throw new IllegalArgumentException("无效的单元格名：" + cellName);
		var String col = matcher.group(1);
		var int row = Integer.parseInt(matcher.group(2)) + rows;
		return col + row;
	}
}
